
package com.plian.system.service.sys.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plian.Tools.CollectionUtil;
import com.plian.system.entity.sys.WfGroup;
import com.plian.system.entity.sys.WfGroupRelation;
import com.plian.system.mapper.sys.WfGroupRelationMapper;
import com.plian.system.service.sys.user.IWfGroupRelationService;
import com.plian.system.service.sys.user.IWfGroupService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户和用户组关系 服务实现类
 *
 * @author jianglei
 * @since 2019-10-23
 */
@Service
@AllArgsConstructor
public class WfGroupRelationServiceImpl extends ServiceImpl<WfGroupRelationMapper, WfGroupRelation> implements IWfGroupRelationService {
    private IWfGroupService wfGroupService;
    /**
     * logger属性.
     */
    private static final Logger logger  = LoggerFactory.getLogger(WfGroupRelationServiceImpl.class);

    @Override
    public void init() {
        Map<String, List<WfGroupRelation>> map = list(new QueryWrapper<WfGroupRelation>().isNotNull("user_id"))
                .stream().collect(Collectors.groupingBy(WfGroupRelation::getUserId));
        List<WfGroup> wfGroups = wfGroupService.list(new QueryWrapper<WfGroup>().eq("is_delete", 0).isNotNull("grade"));

        Map<String, List<WfGroup>> groupMap = new HashMap<>();
        Map<String, String> groupIdMap = new HashMap<>();
        for (WfGroup wfGroup : wfGroups){
            String key = wfGroup.getName().substring(2);
            List<WfGroup> wfGroupList = new ArrayList<>();
            if (groupMap.containsKey(key)){
                wfGroupList = groupMap.get(key);
            }
            groupMap.put(key, wfGroupList);

            if (wfGroup.getName().startsWith("一级")){
                groupIdMap.put(key, wfGroup.getId());
            }
        }

        List<WfGroupRelation> insertList = new ArrayList<>();
        map.forEach ((k,v) -> {


            Map<String, List<WfGroupRelation>> oldOrgMap = v.stream().collect(Collectors.groupingBy(wfGroupRelation -> wfGroupRelation.getOrganizationId()));

            oldOrgMap.forEach((oldOrgId, oldOrgList) -> {
                Map<String, List<WfGroupRelation>> oldKeyMap = oldOrgList.stream().collect(Collectors.groupingBy(wfGroupRelation -> wfGroupRelation.getGroupName().substring(2)));
                List<String> keyList = new ArrayList<>();
                oldKeyMap.forEach((oldKey, oldValue) -> {
                    boolean flag = true;
                    for (WfGroupRelation wfGroupRelation : oldValue){
                        String groupName = wfGroupRelation.getGroupName();
                        if (groupName.startsWith("一级") || groupName.startsWith("二级") ||groupName.startsWith("三级") ||
                                groupName.startsWith("四级")){
                            if (groupName.startsWith("一级")){
                                flag = false;
                                break;
                            }
                        }else {
                            flag = false;
                            break;
                        }
                    }
                    if (flag && !keyList.contains(oldKey)){
                        keyList.add(oldKey);
                    }
                });

                if(CollectionUtil.isNotEmpty(keyList)){
                    for (String key : keyList){
                        insertList.add(WfGroupRelation.builder().id(UUID.randomUUID().toString().replace("-", ""))
                                .userId(k).userName(v.get(0).getUserName()).groupId(groupIdMap.get(key)).groupName("一级" + key)
                                .organizationId(oldOrgId).build());
                    }

                }
            });

        });
        saveBatch(insertList);
    }

    @Override
    public void createFirstGroup() {
        Map<String, List<WfGroupRelation>> map = list(new QueryWrapper<WfGroupRelation>().isNotNull("user_id"))
                .stream().collect(Collectors.groupingBy(WfGroupRelation::getUserId));
        List<WfGroup> wfGroups = wfGroupService.list(new QueryWrapper<WfGroup>().eq("is_delete", 0).isNotNull("grade"));
        List<WfGroup> firstGroup = wfGroups.stream().filter(wfGroup -> wfGroup.getGrade() == 1).collect(Collectors.toList());
        List<WfGroup> excludeFirstGroup = wfGroups.stream().filter(wfGroup -> wfGroup.getGrade() != 1).collect(Collectors.toList());

        Map<String, List<WfGroup>> groupMap = new HashMap<>();
        Map<String, String> groupIdMap = firstGroup.stream().collect(Collectors.toMap(WfGroup::getName, WfGroup::getId, (k1, k2) -> k1));
        for (WfGroup wfGroup : excludeFirstGroup){
            String key = wfGroup.getName().substring(2);
            List<WfGroup> wfGroupList = new ArrayList<>();
            if (groupMap.containsKey(key)){
                wfGroupList = groupMap.get(key);
            }
            groupMap.put(key, wfGroupList);
        }

        List<WfGroupRelation> insertList = new ArrayList<>();
        map.forEach ((k,v) -> {


            Map<String, List<WfGroupRelation>> oldOrgMap = v.stream().collect(Collectors.groupingBy(wfGroupRelation -> wfGroupRelation.getOrganizationId()));

            oldOrgMap.forEach((oldOrgId, oldOrgList) -> {
                Map<String, List<WfGroupRelation>> oldKeyMap = oldOrgList.stream().collect(Collectors.groupingBy(wfGroupRelation -> {
                    String groupName = wfGroupRelation.getGroupName();
                    if (groupName.startsWith("二级") ||groupName.startsWith("三级") ||
                            groupName.startsWith("四级")){
                        groupName = groupName.substring(2);
                    }
                    return groupName;

                }));
                List<String> keyList = new ArrayList<>();
                oldKeyMap.forEach((oldKey, oldValue) -> {
                    boolean flag = true;
                    for (WfGroupRelation wfGroupRelation : oldValue){
                        String groupName = wfGroupRelation.getGroupName();
                        if (groupIdMap.containsKey(groupName) || groupName.startsWith("二级") ||groupName.startsWith("三级") ||
                                groupName.startsWith("四级")){
                            if (groupIdMap.containsKey(groupName)){
                                flag = false;
                                break;
                            }
                        }else {
                            flag = false;
                            break;
                        }
                    }
                    if (flag && !keyList.contains(oldKey)){
                        keyList.add(oldKey);
                    }
                });

                if(CollectionUtil.isNotEmpty(keyList)){
                    for (String key : keyList){
                        insertList.add(WfGroupRelation.builder().id(UUID.randomUUID().toString().replace("-", ""))
                                .userId(k).userName(v.get(0).getUserName()).groupId(groupIdMap.get(key)).groupName(key)
                                .organizationId(oldOrgId).build());
                    }

                }
            });

        });
//        int i = 0;
        saveBatch(insertList);
    }
}
